package net.joyphper.ctrl.security;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import net.joyphper.bean.User;
import net.joyphper.commons.Constants;
import net.joyphper.commons.ResponseJson;
import net.joyphper.commons.exception.AppTranException;
import net.joyphper.commons.security.SecurityUtil;
import net.joyphper.commons.utils.SimpleMailSender;
import net.joyphper.commons.utils.Tools;
import net.joyphper.service.UserService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("net.joyphper.ctrl.security.ForgetPwdCtrl")

public class ForgetPwdCtrl {
	private final String FORGET_PASSWD_CACHE = "forget_passwd_cache";
	private final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private SecurityUtil securityUtil;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RedisTemplate<String, Long> redisTemplate;
	
	@Autowired
	private SimpleMailSender simpleMailSender;
	
	@RequestMapping(value="/auth/forget_pwd.htm",method=RequestMethod.GET)
	public String forget_pwd() {
		return "/auth/forget_pwd";
	}
	
	@RequestMapping(value="/auth/forget_pwd.htm",method=RequestMethod.POST)
	@ResponseBody
	public Object forget_pwd(String loginMail,String captcha) {
		if (!this.securityUtil.compareCaptcha(captcha)){
			return ResponseJson.body(false, "验证码错误！请重新输入验证码");
		}
		
		if(Tools.isEmpty(loginMail)){
			return ResponseJson.body(false,"登录邮箱不能为空！");
		}
		
		User user = this.userService.getUserByLoginMail(loginMail);
		if(user == null) {
			return ResponseJson.body(false,"您 输入的邮箱不存在，请确认是否已经在本站注册！");
		}
		
		String sid = this.securityUtil.getAuth().getSid();
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("loginName", loginMail);
		map.put("time", new Date());
		map.put("sid", sid);
		boolean res = this.simpleMailSender.send(loginMail, "找回密码", "/auth/forget_passwd_mail.html", map);
		if(res){
			BoundValueOperations<String, Long> boundValue = this.redisTemplate.boundValueOps(this.FORGET_PASSWD_CACHE+":"+sid);
			
			boundValue.set(user.getId() , 1800,TimeUnit.SECONDS);
			return ResponseJson.body(true, "重置密码邮件已经发送到"+loginMail+"，请登录邮箱获取！");
		}else{
			return ResponseJson.body(false,"邮件发送失败，请稍后再试");
		}
	}
	
	@RequestMapping(value="/auth/forget_passwd_update.htm",method=RequestMethod.GET)
	public String forget_passwd_update(ModelMap map,String param){
		BoundValueOperations<String, Long> boundValue = this.redisTemplate.boundValueOps(this.FORGET_PASSWD_CACHE+":"+param);
		
		Long uid = boundValue.get();
		if(uid == null){
			map.addAttribute(Constants.MESSAGE_FAIL, "重置密码链接已过期，请重新获取");
			return "/auth/forget_pwd";
		}
		User user  = this.userService.getUserById(uid);
		
		if(user == null){
			map.addAttribute(Constants.MESSAGE_FAIL, "重置密码链接已过期，请重新获取");
			return "/auth/forget_pwd";
		}
		map.addAttribute("param", param);
		map.addAttribute("user", user);
		return "/auth/forget_passwd_update";
	}
	
	@RequestMapping(value="/auth/forget_passwd_update.htm",method=RequestMethod.POST)
	@ResponseBody
	public Object forget_passwd(String loginPwd,String reloginPwd,String captcha,String param) {
		
		if (!this.securityUtil.compareCaptcha(captcha)){
			return ResponseJson.body(false, "验证码错误！请重新输入验证码");
		}
		if(Tools.isEmpty(param)){
			return ResponseJson.body(false, "参数异常，请刷新页面再试！");
		}
		if(Tools.isEmpty(loginPwd)){
			return ResponseJson.body(false, "登录密码不能为空！");
		}
		if(Tools.isEmpty(reloginPwd)){
			return ResponseJson.body(false, "确认密码不能为空！");
		}
		if(!loginPwd.equals(reloginPwd)){
			return ResponseJson.body(false, "登录密码和确认密码不一致！");
		}
		BoundValueOperations<String, Long> boundValue = this.redisTemplate.boundValueOps(this.FORGET_PASSWD_CACHE+":"+param);
		Long uid = boundValue.get();
		
		if(uid == null ){
			return ResponseJson.body(false, "重置密码链接已过期，请重新获取！");
		}
		
		try {
			User user = this.userService.getUserById(uid);
			String pwd = this.securityUtil.genPwd(user.getLoginMail(), loginPwd);
			
			this.userService.updatePwd(pwd, uid);
			
			boundValue.expire(-1, TimeUnit.SECONDS); //从缓存中移除记录
			
			return ResponseJson.body(true,"重置密码成功，请使用新密码登录");
		} catch (AppTranException e) {
			logger.error("找回密码重置用户密码失败",e);
			return ResponseJson.body(false,"系统异常，请稍后再试");
		}
	}
}
